package com.mrx.commons.gateway.handler;

import lombok.Setter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author Mr.X
 * @since 2024/6/2 上午9:31
 */
@Setter
public abstract class DispatchHandler implements ApplicationContextAware {

    protected ApplicationContext applicationContext;

    public abstract void dispatchRequest(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) throws Exception;

    protected void writeResponse(HttpServletResponse response, int code, @Nullable String body) throws Exception {
        try (PrintWriter writer = response.getWriter()) {
            response.setStatus(code);
            if (body != null) {
                writer.write(body);
            }
            writer.flush();
        }
    }

}
